package com.matt.controller.pad;


import com.dotflat.util.excelUtil.StringUtils;
import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.model.StatusResponse;
import com.matt.domain.CheckReportDetail;
import com.matt.domain.ChildrenExtendInfo;
import com.matt.domain.WorkDate;
import com.matt.domain.record.CheckRecord;
import com.matt.foundation.DO.ClassListDO;
import com.matt.foundation.constant.ChildrenConstant;
import com.matt.foundation.constant.PermissionConstant;
import com.matt.foundation.constant.RequestConstant;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.vo.ChildrenListVo;
import com.matt.foundation.vo.ClassesCheckRecordVo;
import com.matt.repository.ChildrenExtendInfoRepository;
import com.matt.repository.WorkDateRepository;
import com.matt.service.CheckReportDetailService;
import com.matt.service.ChildrenService;
import com.matt.service.ClassesService;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.matt.foundation.constant.RequestConstant.TICKET;

@RestController
@RequestMapping("/pad/checkReport")
@Api(tags = "签到签退")
public class PadCheckReportController {

    @Autowired
    private MemVerificationCache cache;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private CheckReportDetailService checkReportDetailService;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private ClassesService classesService;

    @Autowired
    private ChildrenExtendInfoRepository childrenExtendInfoRepository;

    @Autowired
    private WorkDateRepository workDateRepository;

    @RequestMapping(value = "/getCheckReportInfo", method = RequestMethod.POST)
    public StatusResponse getCheckReportInfo(@RequestHeader(TICKET) String ticket, String childId) {

        return StatusResponse.success(checkReportDetailService.findByCreateTimeAndChildId(childId));
    }

    @RequestMapping(value = "/addCheckReport", method = RequestMethod.POST)
    @ApiOperation(value = "增加晨检报告记录")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "childId", value = "宝宝id", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "formData", name = "checkResult", value = "晨检报告元数据", required = true, dataType = "string"),
    })
    public StatusResponse addCheckReport(@RequestHeader(TICKET) String ticket, String childId, String checkResult) {

        String staffId = cache.getStaffId(ticket);
        CheckReportDetail cr = checkReportDetailService.findByCreateTimeAndChildId(childId);
        if (null != cr) {
            return StatusResponse.error("502", "宝宝今天已完成晨检报告");
        } else {

            return StatusResponse.success(checkReportDetailService.addCheckReport(staffId, childId, checkResult));
        }
    }

    @RequestMapping(value = "/getObject", method = RequestMethod.POST)
    public StatusResponse getObject() {

        Map<String, Object> map = new HashMap<>();
        map.put("incomeComposition", "/incomeComposition");
        return StatusResponse.success(map);
    }

    /**
     * 推送预警报告
     * @param ticket
     * @param childrenIds
     * @return
     */
    @RequestMapping(value = "/renew_push", method = RequestMethod.POST)
    private StatusResponse renew_push(@RequestHeader(RequestConstant.TICKET) String ticket, String[] childrenIds) {
        StaffDTO staff = cache.getStaff(ticket);
        AreaDTO area = ssoCallService.getAreaDTO(ticket);
        childrenService.renewPush(staff, area, childrenIds);
        return StatusResponse.success();
    }

    @RequestMapping(value = "/mulit_check_in", method = RequestMethod.POST)
    private StatusResponse mulitCheckIn(@RequestHeader(RequestConstant.TICKET) String ticket, String[] childrenIds) {
        StaffDTO staff = cache.getStaff(ticket);
        AreaDTO area = ssoCallService.getAreaDTO(ticket);

        childrenService.mulitCheckIn(staff, area, childrenIds, ChildrenConstant.CheckStatus.JOIN.codeOf());

//        List<ClassesCheckRecordVo> recordList = childrenService.findClassesCheckRecordByAreaId(area.getId());

        String roleCode = PermissionConstant.Role.TEACHER.codeOf();
        if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_FULL})) {
            roleCode = PermissionConstant.Role.GARDEN_LEADER.codeOf();
        } else if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_DOCTOR})) {
            roleCode = PermissionConstant.Role.DOCTOR.codeOf();
        }

        List<ClassListDO> classesList = classesService.getClassesByStaffId(roleCode, staff.getId(), staff.getAreaId());

        List<ClassesCheckRecordVo> recordList = childrenService.findClassesCheckRecordByClasses(classesList);

        return StatusResponse.success(recordList);
    }

    @RequestMapping(value = "/mulit_check_out", method = RequestMethod.POST)
    private StatusResponse mulitCheckOut(@RequestHeader(RequestConstant.TICKET) String ticket, String[] childrenIds) {
        StaffDTO staff = cache.getStaff(ticket);
        AreaDTO area = ssoCallService.getAreaDTO(ticket);

        childrenService.mulitCheckOut(staff, area, childrenIds);

//        List<ClassesCheckRecordVo> recordList = childrenService.findClassesCheckRecordByAreaId(area.getId());
//        StaffDTO staff = cache.getStaff(ticket);

        String roleCode = PermissionConstant.Role.TEACHER.codeOf();
        if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_FULL})) {
            roleCode = PermissionConstant.Role.GARDEN_LEADER.codeOf();
        } else if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_DOCTOR})) {
            roleCode = PermissionConstant.Role.DOCTOR.codeOf();
        }

        List<ClassListDO> classesList = classesService.getClassesByStaffId(roleCode, staff.getId(), staff.getAreaId());

        List<ClassesCheckRecordVo> recordList = childrenService.findClassesCheckRecordByClasses(classesList);

        return StatusResponse.success(recordList);
    }

    @RequestMapping(value = "/leave_reason", method = RequestMethod.POST)
    private StatusResponse leaveReasons(@RequestHeader(RequestConstant.TICKET) String ticket, String childrenId,
                                        MultipartFile file, Integer checkType, String sickName, String specialRecord,
                                        String exceptionName, Integer healthyTag, String weight, String height,
                                        String header, String remark) {


        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        AreaDTO area = ssoCallService.getAreaDTO(ticket);

        CheckRecord record = childrenService.checkIn(area, staff, checkType, childrenId, file, sickName, specialRecord,
                exceptionName, healthyTag, weight, height, header, remark);
        //    pushCheck(record);
        return StatusResponse.success(record);
    }

    @RequestMapping(value = "/check_in", method = RequestMethod.POST)
    private StatusResponse checkIn(@RequestHeader(RequestConstant.TICKET) String ticket, String childrenId,
                                   MultipartFile file, Integer checkType, String sickName, String specialRecord,
                                   String exceptionName, Integer healthyTag, String weight, String height,
                                   String header, String remark, Boolean alert) {


        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        AreaDTO area = ssoCallService.getAreaDTO(ticket);

        CheckRecord record = childrenService.checkIn(area, staff, checkType, childrenId, file, sickName, specialRecord,
                exceptionName, healthyTag, weight, height, header, remark);
        //    pushCheck(record);
        return StatusResponse.success(record);
    }

    @RequestMapping(value = "/check_out", method = RequestMethod.POST)
    private StatusResponse checkOut(@RequestHeader(RequestConstant.TICKET) String ticket, String childrenId, MultipartFile file) {
        CheckRecord record = childrenService.checkOut(cache.getStaff(ticket), ssoCallService.getAreaDTO(ticket), childrenId, file);
        return StatusResponse.success(record);
    }

    @ApiOperation("园区所有宝宝签到状态")
    @RequestMapping(value = "/check_record", method = RequestMethod.POST)
    public StatusResponse checkRecord(@RequestHeader(TICKET) String ticket) {

        StaffDTO staff = cache.getStaff(ticket);

        String roleCode = PermissionConstant.Role.TEACHER.codeOf();
        if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_FULL})) {
            roleCode = PermissionConstant.Role.GARDEN_LEADER.codeOf();
        } else if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_DOCTOR})) {
            roleCode = PermissionConstant.Role.DOCTOR.codeOf();
        }

        List<ClassListDO> classesList = classesService.getClassesByStaffId(roleCode, staff.getId(), staff.getAreaId());

        List<ClassesCheckRecordVo> recordList = childrenService.findClassesCheckRecordByClasses(classesList);

        return StatusResponse.success(recordList);
    }

    @ApiOperation("园区所有宝宝签到简略报告")
    @RequestMapping(value = "/getAreaCheckInfo", method = RequestMethod.POST)
    public StatusResponse getAreaCheckInfo(@RequestHeader(TICKET) String ticket) {
        Map m = new HashMap<>();
        int absentCount = 0;//缺席孩子数量
        int normalCount = 0;//正常孩子数量
        int checkOutCount = 0;//离园数量
        int checkRejectCount = 0;//拒绝入园孩子数量
        int levalCount = 0;//请假孩子数量
        int noHealthyCount = 0;//不健康孩子数量

        String areaId = cache.getAreaId(ticket);
        List<String> childrenIdList = new ArrayList<>();
        List<ChildrenListVo> areaChildrenList = childrenService.getHasChildrenByArea(areaId);
        for (ChildrenListVo vo : areaChildrenList) {
            childrenIdList.add(vo.getId());
        }

        List<ChildrenExtendInfo> extendInfoList = childrenExtendInfoRepository.findByChildrenIdIn(childrenIdList);
        if (extendInfoList.size() > 0) {

            List<ChildrenExtendInfo> absentList = extendInfoList.stream().filter(o -> o.getCheckStatus() == 0).collect(Collectors.toList());//缺席
            absentCount = absentList.size();

            List<ChildrenExtendInfo> normalList = extendInfoList.stream().filter(o -> o.getCheckStatus() == 1).collect(Collectors.toList());//入园/正常
            normalCount = normalList.size();

            List<ChildrenExtendInfo> checkOutList = extendInfoList.stream().filter(o -> o.getCheckStatus() == 2).collect(Collectors.toList());//离园数量
            checkOutCount = checkOutList.size();

            List<ChildrenExtendInfo> checkRejectList = extendInfoList.stream().filter(o -> o.getCheckStatus() == 3).collect(Collectors.toList());//拒绝入园孩子数量
            checkRejectCount = checkRejectList.size();

            List<ChildrenExtendInfo> levalList = extendInfoList.stream().filter(o -> o.getCheckStatus() == 4).collect(Collectors.toList());//请假
            levalCount = levalList.size();

            List<ChildrenExtendInfo> noHealthyList = extendInfoList.stream().filter(o -> o.getHealthyStatus() == 1).collect(Collectors.toList());//不健康
            noHealthyCount = noHealthyList.size();
        }

        int studentCount = childrenIdList.size();

        m.put("absentCount", absentCount);
        m.put("normalCount", normalCount);
        m.put("checkOutCount", checkOutCount);
        m.put("checkRejectCount", checkRejectCount);
        m.put("levalCount", levalCount);
        m.put("noHealthyCount", noHealthyCount);
        m.put("studentCount", studentCount);

        return StatusResponse.success(m);
    }


    @RequestMapping(value = "/check_in_v2", method = RequestMethod.POST)
    private StatusResponse checkInV2(@RequestHeader(RequestConstant.TICKET) String ticket, String childrenId,
                                     MultipartFile file, Integer checkType, String sickName, String specialRecord,
                                     String exceptionName, Integer healthyTag, String weight, String height,
                                     String header, String remark, Boolean alert, Integer day, Integer isHoliday) {


        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        AreaDTO area = ssoCallService.getAreaDTO(ticket);

        CheckRecord record = childrenService.checkIn(area, staff, checkType, childrenId, file, sickName, specialRecord,
                exceptionName, healthyTag, weight, height, header, remark, day, isHoliday, ticket);
        //    pushCheck(record);
        return StatusResponse.success(record);
    }


    @RequestMapping(value = "/mulit_check_inV2", method = RequestMethod.POST)
    private StatusResponse mulitCheckInV2(@RequestHeader(RequestConstant.TICKET) String ticket, String[] childrenIds) {
        StaffDTO staff = cache.getStaff(ticket);
        AreaDTO area = ssoCallService.getAreaDTO(ticket);
        childrenService.mulitCheckInV2(ticket, area, staff, 1, childrenIds);
        String roleCode = PermissionConstant.Role.TEACHER.codeOf();
        if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_FULL})) {
            roleCode = PermissionConstant.Role.GARDEN_LEADER.codeOf();
        } else if (ssoCallService.checkStaffPermission(ticket, new String[]{PermissionConstant.TEACH_CLASSES_DOCTOR})) {
            roleCode = PermissionConstant.Role.DOCTOR.codeOf();
        }
        List<ClassListDO> classesList = classesService.getClassesByStaffId(roleCode, staff.getId(), staff.getAreaId());
        List<ClassesCheckRecordVo> recordList = childrenService.findClassesCheckRecordByClasses(classesList);
        return StatusResponse.success(recordList);
    }

}
